<template>
  <div class="playlist-song">

    <el-table highlight-current-row @current-change="handleCurrentChange" :data="curPagesongs" style="width: 100%;"
      stripe border :default-sort="{prop: 'curPagesongs', order: 'descending'}">
      <el-table-column prop="name" label="标题" sortable></el-table-column>
      <el-table-column width="250" label="歌手" sortable>
        <template v-slot="{row}">
          <div class="authors">
            <div v-for="(item,index) of musicauthor(row)" :key="index+'name'"
              @click.stop="$router.push({ name: 'artistAccount', query: { id:item.id } });" class="author">
              {{item.name}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="al.name" width="300" label="专辑" sortable>
        <template v-slot="{ row }">
          <div @click.stop="$router.push({ name:'album',query:{ id:row.al.id }})" class="album">{{ row.al.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="dt" width="80" label="时间" sortable>
        <template v-slot="{ row }">{{ (row.dt / 1000) | timeFormat }}</template>
      </el-table-column>
    </el-table>
    <div v-show="count>=pageSize" class="pageset">
      <el-pagination :page-size.sync="pageSize" :current-page.sync="curPage" @current-change="getplaylisttrack()"
        layout="prev, pager, next" :total="count" background></el-pagination>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getplaylisttrackAPI } from "@/api/playlist.js";
export default {
  name: "playlist-song",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    id: {
      require: true,
    },
    count: {
      require: true,
    },
    search: {},
  },
  data() {
    //这里存放数据
    return {
      loading: true,
      //歌单全部歌曲
      songs: [],
      //当前页面歌曲
      curPagesongs: [],
      //搜索当前页面歌曲
      filtercurPagesongs: [],
      limit: 0,
      curPage: 1,
      pageSize: 30,
      currentMusic: {},
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    // 实现搜索功能
    search(val) {
      if (val) {
        console.log(val + "有数值");
        this.curPagesongs = this.filtercurPagesongs.filter((item) =>
          item.name.toUpperCase().includes(this.search.toUpperCase())
        );
      } else if (val == "") {
        this.curPagesongs = this.filtercurPagesongs;
      }
    },
  },
  //方法集合
  methods: {
    // element组件，获取点击的音乐的信息
    handleCurrentChange(val) {
      this.currentMusic = val;
      // console.log("点击的歌曲信息-歌单", val);
      // 把播放状态转为正在播放
      this.$store.state.musicisPlay = true;
      // 提交数据到vuex，通过vuex把数据传递给播放组件
      this.$store.commit("addMusictoMuiscListbyNewmusic", this.songs);
      this.$store.commit("getcurrentIndex", val);
      this.$store.dispatch("getMusicDetail", val);
    },
    async getplaylisttrack() {
      try {
        this.limit = (this.curPage - 1) * 30;
        // const data = await getplaylisttrackAPI(this.id, 30, this.limit)
        // console.log(data.data.songs);
        this.curPagesongs = this.songs.slice(this.limit, this.limit + 30);
        this.filtercurPagesongs = this.songs.slice(this.limit, this.limit + 30);
        // 页面滚动优化用户体验
        if (document.documentElement.scrollTop != 0) {
          document.documentElement.scrollTop = 370;
        }
      } catch (error) {
        console.log(error + "获取歌单获取歌曲失败");
      }
    },
    async getAllplaylisttrack() {
      try {
        const data = await getplaylisttrackAPI(this.id, 500, 0);
        this.songs = data.data.songs;
        this.$store.commit("setcurrentSongs", this.songs);
        this.getplaylisttrack();
      } catch (error) {
        console.log(error + "获取全部歌单失败");
      }
    },

    //计算作者名字
    musicauthor(currentMusic) {
      if (currentMusic) {
        if (currentMusic.ar) {
          let name = [];
          currentMusic.ar.forEach((element) => {
            name.push(element);
          });
          return name;
        }
        return "作者";
      } else {
        return "作者";
      }
      //   if (currentMusic) {
      //     let name = "";
      //     if (currentMusic.ar.length == 1) {
      //       return currentMusic.ar[0].name;
      //     } else if (currentMusic.ar.length > 1) {
      //       for (let index = 0; index < currentMusic.ar.length; index++) {
      //         const element = currentMusic.ar[index].name;
      //         if (name == "") {
      //           name = name + "" + element;
      //         } else {
      //           name = name + "/" + element;
      //         }
      //       }
      //       return name;
      //     }
      //   } else {
      //     return "作者";
      //   }
      //   return "";
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getAllplaylisttrack();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang='less'>
.pageset {
  display: flex;
  justify-content: center;
  .el-pagination {
    margin-top: 50px;
    margin-bottom: 80px;
  }
}
.authors {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  .author {
    display: inline-block;
    cursor: pointer;
    margin-right: 5px;
  }
}
.album {
  cursor: pointer;
  display: inline-block;
}
</style>